package ru.resumeService.service.db;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.*;

public class ConnectionFactory {
    private static ConnectionFactory connectionFactory;
    private static DataSource dataSource;

    private ConnectionFactory() {
    }

    public static ConnectionFactory getFactory() {
        if (connectionFactory != null) {
            return connectionFactory;
        } else {
            init();
            connectionFactory = new ConnectionFactory();
            return connectionFactory;
        }
    }

    private static void init() {
        Context initContext = null;
        try {
            initContext = new InitialContext();
            Context envContext  = (Context)initContext.lookup("java:/comp/env");
            dataSource = (DataSource)envContext.lookup("jdbc/hr");
        } catch (NamingException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    public Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return null;
    }
}
